package pdi.IO;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.iterators.ArrayIterator;
import org.apache.commons.io.FilenameUtils;

import pdi.core.Image;

public class SeqImgReader extends ImgReader {


	private String imagesDir;
	private String annnotationsDir;
	protected ArrayIterator<File> imgsIterator;


	public SeqImgReader(String dataSetDir) {
		this.imagesDir = Paths.get(dataSetDir,"images").toString();
		this.annnotationsDir = Paths.get(dataSetDir,"annotations").toString();
	}

	@Override
	public void open() {
		//check if exist
		File imgDir = new File(imagesDir);
		if(!imgDir.exists() || !imgDir.isDirectory())
			throw new IllegalArgumentException("There isn't a derectory on the requested path");

		File[] files = getAllImageFiles(imagesDir);	
		this.imgsIterator = new ArrayIterator<File>(files);
	}

	@Override
	public void close() {
		this.imgsIterator.reset();
		this.imgsIterator = null;

	}

	@Override
	public Image readNext() {

		if(this.imgsIterator == null )
			throw new IllegalArgumentException("Directory without images, wrong directory or unopen reader");

		Image img = null;

		try {
			if(this.imgsIterator.hasNext()){
				File imgFile = this.imgsIterator.next();
				String anntPath = FilenameUtils.removeExtension(Paths.get(annnotationsDir,imgFile.getName()).toString()) + ".txt";			
				File annotationFile = new File(anntPath);

				img = new Image(imgFile.getPath(), annotationFile.getPath());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return img;
	}



	@Override
	public List<Image> readAll() {
		
		open();

		//read all images and put in a list
		List<Image> ret = new ArrayList<Image>();
		Image img = null;
		while((img = readNext()) != null)		
			ret.add(img);

		close();
		
		return ret;
	}


}
